<template>
  <el-dialog
      :model-value="addDialogVisible"
      title="学员信息添加"
      width="50%"
      draggable
      center
      @close="handleClose"
  >
    <el-form ref="addfrom" :model="form" label-width="80px" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学员号" prop="userId">
            <el-input v-model="form.userId" maxlength="10" show-word-limit/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" maxlength="10" type="password" show-password/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="name">
            <el-input v-model="form.name" maxlength="10"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="form.idCard" @change="getAge(form.idCard)"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="form.age" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属教练" prop="coachId">
            <el-select v-model="form.coachId" clearable placeholder="教练">
              <el-option
                  v-for="item in CID"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12"></el-col>
        <el-col :span="12">
          <el-form-item label="入学时间" prop="date">
            <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="入学时间"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleCommit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref} from "vue";
import {getAllTeacher} from "@/api/teacher";
import {ElMessage} from "element-plus";
import {InsertStudent} from "@/api/student"
import { idCardValidity , phone} from "@/utils/IDjiaoyan"
//获取父组件方法或传值
const props = defineProps({
  initGetStudents:{
    type:Function,
    required:true
  }
})

//教练options值
const CID=[]
const GetCID=()=>{
  getAllTeacher({pageNum:1,pageSize:999999}).then(res=>{
    res.data.list.forEach(item=>{
      CID.push(item.id)
    })
  })
}
GetCID()
//初始化表单
const form = ref({})
const rules =ref({
  userId:[
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password:[
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  name:[
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  sex:[
    { required: true, message: '请输入性别', trigger: 'blur' }
  ],
  mobile:[
      { required: true, message: '手机号不能为空' },
    { required: true, validator: phone, trigger: "blur" }
  ],
  age:[
    { required: true, message: '请输入年龄' },
    { type: 'number', message: '年龄必须为数字' },
  ],
  idCard: [
    { required: true, message: "请输入个人身份证号", trigger: "blur" },
    { pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,message: '请输入正确的个人身份证号',trigger: 'blur' },
    { required: true,validator: idCardValidity, trigger: 'blur' },
  ],
  type:[
    { required: true, message: '请选择驾照类型', trigger: 'blur' }
  ],
  coachId:[
    { required: true, message: '请选择所属教练', trigger: 'blur' }
  ],
  date:[
    { required: true, message: '请输入入学日期', trigger: 'blur' }
  ],
})
const Emits=defineEmits(['update:modelValue'])

//表单重置
const resetupdatefrom = () =>{
  addfrom.value.resetFields()
}

const handleClose=()=>{
  resetupdatefrom()
  Emits('update:modelValue',false)
}
const addfrom=ref(null)

//性别，年龄生成
//iden参数是身份证号
const getAge = (iden) => {
  let val = iden.length;
  let myDate = new Date();
  let month = myDate.getMonth() + 1;
  let day = myDate.getDate();
  let age = 0;
  let sex = '';

  if (val === 18) {
    age = myDate.getFullYear() - iden.substring(6, 10) - 1;
    if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;
    sex = iden.substring(16, 17)%2 == 1 ? "男" : "女";
  }
  //把算出的年龄给复制给from表单
  form.value.age = age;
  form.value.sex = sex;
}
//添加
const handleCommit=()=>{
  addfrom.value.validate(async (valid) => {
    if (valid) {
      await InsertStudent({
        userId:('1-'+form.value.userId),
        password:form.value.password,
        name:form.value.name,
        sex:form.value.sex,
        mobile:form.value.mobile,
        age:form.value.age,
        idCard:form.value.idCard,
        date:form.value.date,
        coachId:form.value.coachId
      }).then(res=>{
        if(res.code===20011){
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
        }else {
          ElMessage({
            message: '用户已存在',
            type: 'error',
          })
        }
        props.initGetStudents()
        addfrom.value.resetFields()
      })
    } else {
      addfrom.value.resetFields()
      console.log('error submit!')
    }
  })
  handleClose()
}
</script>

<style scoped>

</style>